//
//  MutaChatViewController.swift
//  MSinger
//
//  Created by Kevin on 2018/3/14.
//  Copyright © 2018年 InitialC. All rights reserved.
//

import UIKit
import SnapKit
import AVFoundation

class MutaChatViewController: UIViewController {
    
    var content = String() // 发送内容
    var page = Int()
    var chatMessageArray = [MutaChatModel]() //model
    var inputViewHight = CGFloat()
    var imgPickerVC = UIImagePickerController() //相机
    //保存cell图片相关
    var coverView = UIView()
    var coverImgView = UIImageView()
    var coverImg = String()
    var coverImgSize = CGSize()
    //
    var deleteRow = Int()
    var textViewHeight = CGFloat()
    var keyboardHeight = CGFloat()
    // 键盘弹出时间
    var showKeyBoardDuration = Double()
    var hideKeyBoardDuration = Double()

    lazy var moreView: MutaMoreView = {
        let view = MutaMoreView()
        view.backgroundColor = UIColor.white
        view.frame = CGRect(x: 0, y: kZWScreenH - 215, width: kZWScreenW, height: 215)
        let item0 = MutaMoreItemView.createMoreItemWithTitle(name: "照片", withImage: "sharemore_pic")
        let item1 = MutaMoreItemView.createMoreItemWithTitle(name: "拍摄", withImage: "sharemore_video")
        let item2 = MutaMoreItemView.createMoreItemWithTitle(name: "表白", withImage: "sharemore_voiceinput")
        let item3 = MutaMoreItemView.createMoreItemWithTitle(name: "分手", withImage: "sharemore_myfav")
        let item4 = MutaMoreItemView.createMoreItemWithTitle(name: "举报", withImage: "sharemore_sight")
        let item5 = MutaMoreItemView.createMoreItemWithTitle(name: "反馈", withImage: "sharemore_wallet")
        view.itemsAry = [item0, item1, item2, item3, item4, item5]
        return view
    }()
    
    lazy var emojiView: MutaEmojiView = {
        let view = MutaEmojiView()
        view.backgroundColor = UIColor.white
        view.frame = CGRect(x: 0, y: kZWScreenH - 215, width: kZWScreenW, height: 215)
        return view
    }()
    
    lazy var chatTableView: MutaChatTableView = {
        let tableView = MutaChatTableView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    lazy var chatInputView: MutaChatInputView = {
        let view = MutaChatInputView()
        view.inputTextView.delegate = self
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        page = 1
        self.view.backgroundColor = UIColor.gray
        self.creatView()
        self.testModelData()
        self.chatConfig()
        self.chatRefresh()
        self.chatTableView.mj_header.beginRefreshing()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name.init("长按手势"), object: nil, queue: nil) { (noti) in
            if self.chatInputView.inputTextView.isFirstResponder {
                self.chatInputView.inputTextView.inputNextResponder = self
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: InputDelegate
extension MutaChatViewController: MutaChatInputDelegate, UIGestureRecognizerDelegate {
    func chatInputChanged(_ inputView: MutaChatInputView, _ fromStatus: MutaChatInPutStatus, _ toStatus: MutaChatInPutStatus) {
        if toStatus == .StatusShowKeyboard {
            //显示键盘view
            self.emojiView.removeFromSuperview()
            self.moreView.removeFromSuperview()
            return
        }else if toStatus == .StatusShowEmoji {
            //根据fromStatus判断高度变化
            if fromStatus == .StatusNone {
                self.view.addSubview(self.emojiView)
                self.inputViewIsShown(isShow: true)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                    self.chatTableView.scrollToBottom()
                }
                
            }else {
                self.view.addSubview(self.emojiView)
                UIView.animate(withDuration: 0.3, animations: {
                    self.inputViewIsShown(isShow: true)
                }, completion: { (finished) in
                    self.moreView.removeFromSuperview()
                    self.chatTableView.scrollToBottom()
                })
            }
        }else if toStatus == .StatusShowMore {
            if fromStatus == .StatusNone {
                self.view.addSubview(moreView)
                self.inputViewIsShown(isShow: true)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                    self.chatTableView.scrollToBottom()
                }
            }else {
                self.view.addSubview(moreView)
                UIView.animate(withDuration: 0.3, animations: {
                    self.inputViewIsShown(isShow: true)
                }, completion: { (finished) in
                    self.emojiView.removeFromSuperview()
                    self.chatTableView.scrollToBottom()
                })
            }
        }
    }
    
    //手势
    @objc func panScrollToBottom(gesture: UIPanGestureRecognizer) {
        guard gesture.state == .began else {
            return
        }
        self.gestureJudge()
    }
    
    @objc func tapScrollToBottom(gesture: UITapGestureRecognizer) {
        guard gesture.state == .ended else {
            return
        }
        self.gestureJudge()
    }
    
    func gestureJudge() {
        self.chatInputView.chatStatus = .StatusNone
        self.chatInputView.emojiBtnEmojiImage()
        self.chatInputView.addBtnAddImage()
        
        guard self.view.subviews.contains(emojiView) else {
            guard self.view.subviews.contains(moreView) else {
                guard chatInputView.inputTextView.isFirstResponder else {
                    return
                }
                chatInputView.inputTextView.resignFirstResponder()
                self.inputViewIsShown(isShow: false)
                chatTableView.scrollToBottom()
                return
            }
            moreView.removeFromSuperview()
            self.inputViewIsShown(isShow: false)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                self.chatTableView.scrollToBottom()
            }
            return
        }
        emojiView.removeFromSuperview()
        self.inputViewIsShown(isShow: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
            self.chatTableView.scrollToBottom()
        }
        return
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        let bool1 = self.view.subviews.contains(emojiView)
        let bool2 = self.view.subviews.contains(moreView)
        let bool3 = chatInputView.inputTextView.isFirstResponder
        if bool1 || bool2 || bool3 {
            return true
        }
        return false
    }
}


//MARK: 相册
extension MutaChatViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //相册
    func getImgFromPhoto() {
        imgPickerVC.sourceType = UIImagePickerControllerSourceType.photoLibrary
        self.present(imgPickerVC, animated: true, completion: nil)
    }
    // 相机
    func getImgFromCamera() {
        // 调用相机之前判断设备是否有摄像头
        if !UIImagePickerController.isSourceTypeAvailable(.camera) {
            return
        }
        let statusVideo = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if statusVideo == .notDetermined {
            print("获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限")
            return
        }
        if statusVideo == .denied {
            print("获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限")
            return
        }
        imgPickerVC.sourceType = UIImagePickerControllerSourceType.camera
        imgPickerVC.videoQuality = UIImagePickerControllerQualityType.typeHigh
        imgPickerVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.photo
        self.present(imgPickerVC, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let img = info[UIImagePickerControllerEditedImage] as! UIImage
        //TODO: 上传图片OSS
        self.sendImg(img)
        picker.dismiss(animated: true, completion: nil)
    }
    
    func sendImg(_ selectedImage: UIImage) {
        let model = MutaChatModel()
        model.messageContent = content
        model.messageImg = "IMG_0007"
        model.messageType = .sendToMe
        model.onlyTime = false
        let user = UserInfoMaster()
        user.name = "KiKi"
        user.header = "header1"
        user.userId = "456"
        model.sendUserInfo = user
        model.receiveUserInfo = user
        self.chatMessageArray.append(model)
        self.chatTableView.chatData = self.chatMessageArray
        chatTableView.scrollToBottom()
    }
}
//MARK: 键盘的高度要重新计算
extension MutaChatViewController {
    func creatView() {
        self.view.addSubview(chatTableView)
        self.view.addSubview(chatInputView)
        chatInputView.snp.makeConstraints { (make) in
            make.width.equalTo(kZWScreenW)
            make.height.equalTo(52)
            make.bottom.equalToSuperview()
        }
        chatTableView.snp.makeConstraints { (make) in
            make.width.equalTo(kZWScreenW)
            make.bottom.equalTo(chatInputView.snp.top)
            make.top.equalToSuperview().offset(64)
        }
    }
    
    func chatConfig() {
        chatInputView.chatStatus = .StatusNone
        chatInputView.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(showView(noti:)), name: NSNotification.Name.init("图片长按手势启动"), object: nil)
        //手势
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapScrollToBottom(gesture:)))
        chatTableView.addGestureRecognizer(tap)
        let pan = UIPanGestureRecognizer(target: self, action: #selector(panScrollToBottom(gesture:)))
        pan.delegate = self
        chatTableView.addGestureRecognizer(pan)
        chatTableView.toVCSegue = {id in
            print(id)
        }
        chatTableView.showImgSegue = {img, size in
            guard !self.view.subviews.contains(self.emojiView) else {
                self.emojiView.removeFromSuperview()
                self.inputViewIsShown(isShow: false)
                return
            }
            guard !self.view.subviews.contains(self.moreView) else {
                self.moreView.removeFromSuperview()
                self.inputViewIsShown(isShow: false)
                return
            }
            guard !self.chatInputView.inputTextView.isFirstResponder else {
                self.inputViewIsShown(isShow: false)
                self.chatInputView.inputTextView.resignFirstResponder()
                return
            }
            self.coverImg = img
            self.coverImgSize = size as! CGSize
            self.showBigImgView()
        }
        chatTableView.deleteSegue = {row in
            self.deleteRow = row as! Int
            self.chatMessageArray.remove(at: self.deleteRow)
            self.chatTableView.chatData = self.chatMessageArray
        }
        
        //相册/相机
        imgPickerVC.delegate = self
        imgPickerVC.modalTransitionStyle = .flipHorizontal
        imgPickerVC.allowsEditing = true
        
        moreView.moreSegue = {id in
            let tpye = id as! Int
            switch tpye {
            case 0: //相册
                self.getImgFromPhoto()
                break
            case 1: //相机
                self.getImgFromCamera()
                break
            case 2: //表白
                break
            case 3: //分手
                break
            case 4: //举报
                break
            case 5: //反馈
                break
            default:
                break
            }
        }
    }
}
